<template>
  <el-drawer
    v-model="visibleLocal"
    title="快速建档"
    size="640px"
    destroy-on-close
    @close="handleClose"
  >
    <div class="quick-create">
      <el-steps :active="activeStep" align-center finish-status="success" class="mb-4">
        <el-step title="账号信息" />
        <el-step title="企业资料" />
        <el-step title="开票信息" />
        <el-step title="地址信息" />
      </el-steps>

      <div class="step-container">
        <el-form
          v-show="activeStep === 0"
          ref="accountFormRef"
          :model="accountForm"
          :rules="accountRules"
          label-width="100px"
        >
          <el-form-item label="登录手机号" prop="phone">
            <el-input v-model="accountForm.phone" placeholder="请输入11位手机号" clearable />
          </el-form-item>
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="accountForm.password" placeholder="至少6位字符" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="accountForm.confirmPassword" placeholder="请再次输入密码" show-password />
          </el-form-item>
          <el-form-item label="联系人姓名" prop="real_name">
            <el-input v-model="accountForm.real_name" placeholder="用于联系人信息" clearable />
          </el-form-item>
          <el-form-item label="联系人昵称" prop="nickname">
            <el-input v-model="accountForm.nickname" placeholder="用于系统显示的昵称" clearable />
          </el-form-item>
        </el-form>

        <el-form
          v-show="activeStep === 1"
          ref="companyFormRef"
          :model="companyForm"
          :rules="companyRules"
          label-width="110px"
        >
          <el-form-item label="企业名称" prop="company_name">
            <el-input v-model="companyForm.company_name" placeholder="营业执照上的企业名称" clearable />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="license_code">
            <el-input v-model="companyForm.license_code" placeholder="请输入18位社会信用代码" clearable />
          </el-form-item>
          <el-form-item label="法人代表" prop="legal_rep">
            <el-input v-model="companyForm.legal_rep" placeholder="请输入法人代表姓名" clearable />
          </el-form-item>
          <el-form-item label="注册地址" prop="address">
            <el-input
              v-model="companyForm.address"
              placeholder="请输入营业执照上的注册地址"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 3 }"
            />
          </el-form-item>
          <el-form-item label="所属区域" prop="region_id">
            <el-select
              v-model="companyForm.region_id"
              placeholder="请选择业务归属区域"
              filterable
              clearable
            >
              <el-option
                v-for="region in regionOptions"
                :key="region.value"
                :label="region.label"
                :value="region.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="经营范围" prop="scope">
            <el-input
              v-model="companyForm.scope"
              placeholder="选填：经营范围、主营业务"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
          <el-form-item label="执照图片" prop="license_photo">
            <el-upload
              class="license-upload"
              drag
              accept="image/*"
              :show-file-list="false"
              :http-request="handleLicenseUpload"
              :before-upload="beforeLicenseUpload"
            >
              <template v-if="companyForm.license_photo">
                <div class="license-preview">
                  <img :src="companyForm.license_photo" alt="营业执照" class="license-preview__image" />
                  <div class="license-preview__actions">
                    <el-button
                      text
                      type="primary"
                      :icon="useRenderIcon('ep:view')"
                      @click.stop="previewLicense"
                    >
                      预览
                    </el-button>
                    <el-button
                      text
                      type="danger"
                      :icon="useRenderIcon('ep:delete')"
                      @click.stop="removeLicensePhoto"
                    >
                      移除
                    </el-button>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="license-upload__placeholder">
                  <el-icon class="license-upload__icon">
                    <component :is="useRenderIcon('ep:upload-filled')" />
                  </el-icon>
                  <div class="license-upload__text">
                    <p class="title">将文件拖到此处，或点击上传</p>
                    <p class="hint">支持 JPG/PNG，大小不超过 2MB</p>
                  </div>
                </div>
              </template>
            </el-upload>
            <el-progress
              v-if="licenseUploading"
              class="license-progress"
              :percentage="licenseUploadProgress"
              :stroke-width="4"
              :striped="true"
              :striped-flow="true"
            />
          </el-form-item>
        </el-form>

        <el-form
          v-show="activeStep === 2"
          ref="invoiceFormRef"
          :model="invoiceForm"
          :rules="invoiceEnabled ? invoiceRules : {}"
          label-width="110px"
        >
          <el-form-item label="是否填写">
            <el-switch v-model="invoiceEnabled" active-text="填写开票信息" inactive-text="暂不填写" />
          </el-form-item>
          <template v-if="invoiceEnabled">
            <el-form-item label="开票抬头" prop="invoice_title">
              <el-input
                v-model="invoiceForm.invoice_title"
                placeholder="请输入发票抬头"
                clearable
              />
            </el-form-item>
            <el-form-item label="纳税识别号" prop="invoice_taxno">
              <el-input
                v-model="invoiceForm.invoice_taxno"
                placeholder="请输入纳税人识别号"
                clearable
              />
            </el-form-item>
            <el-form-item label="开户银行" prop="bank_name">
              <el-input v-model="invoiceForm.bank_name" placeholder="选填：开户银行" clearable />
            </el-form-item>
            <el-form-item label="银行账户" prop="bank_account">
              <el-input v-model="invoiceForm.bank_account" placeholder="选填：银行账号" clearable />
            </el-form-item>
            <el-form-item label="银行户名" prop="bank_account_name">
              <el-input v-model="invoiceForm.bank_account_name" placeholder="选填：开户名称" clearable />
            </el-form-item>
            <el-form-item label="联系姓名" prop="contact_name">
              <el-input v-model="invoiceForm.contact_name" placeholder="选填：开票联系人" clearable />
            </el-form-item>
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input v-model="invoiceForm.contact_phone" placeholder="选填：联系电话" clearable />
            </el-form-item>
            <el-form-item label="联系邮箱" prop="contact_email">
              <el-input v-model="invoiceForm.contact_email" placeholder="选填：联系邮箱" clearable />
            </el-form-item>
          </template>
        </el-form>

        <div v-show="activeStep === 3" class="address-step">
          <div class="flex items-center justify-between mb-3">
            <span class="text-sm text-gray-500">请至少保留一个收货地址</span>
            <el-space>
              <el-button text type="primary" :icon="useRenderIcon('ep:document-copy')" @click="copyCompanyAddress">
                复制企业地址
              </el-button>
              <el-button text type="primary" :icon="useRenderIcon('ep:plus')" @click="addAddress('shipping')">
                新增收货地址
              </el-button>
              <el-button text type="primary" :icon="useRenderIcon('ep:plus')" @click="addAddress('billing')">
                新增开票地址
              </el-button>
            </el-space>
          </div>
          <el-empty v-if="!addressList.length" description="暂无地址，请新增" />
          <div v-else class="address-list">
            <el-card
              v-for="address in addressList"
              :key="address.key"
              class="mb-3"
              shadow="never"
              body-style="{ padding: '16px 16px 8px' }"
            >
              <template #header>
                <div class="flex items-center justify-between">
                  <div class="flex items-center space-x-3">
                    <el-tag size="small" effect="plain">
                      {{ address.address_type === "shipping" ? "收货地址" : "开票地址" }}
                    </el-tag>
                    <el-switch
                      v-if="address.address_type === 'shipping'"
                      v-model="address.is_default"
                      active-text="默认收货"
                      @change="handleDefaultToggle(address)"
                    />
                  </div>
                  <el-button
                    link
                    type="danger"
                    :icon="useRenderIcon('ep:delete')"
                    @click="removeAddress(address.key)"
                  >
                    移除
                  </el-button>
                </div>
              </template>
              <el-form
                :model="address"
                :rules="addressRules"
                :ref="setAddressFormRef(address.key)"
                label-width="90px"
              >
                <el-form-item label="联系人" prop="contact_name">
                  <el-input v-model="address.contact_name" placeholder="请输入联系人姓名" clearable />
                </el-form-item>
                <el-form-item label="联系电话" prop="contact_phone">
                  <el-input v-model="address.contact_phone" placeholder="手机号或座机" clearable />
                </el-form-item>
                <el-form-item label="所在省市" required>
                  <div class="grid grid-cols-3 gap-2 w-full">
                    <el-input v-model="address.province" placeholder="省" clearable />
                    <el-input v-model="address.city" placeholder="市" clearable />
                    <el-input v-model="address.district" placeholder="区 / 县" clearable />
                  </div>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                  <el-input
                    v-model="address.address"
                    placeholder="街道、门牌号等"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 3 }"
                  />
                </el-form-item>
                <el-form-item label="邮政编码" prop="postal_code">
                  <el-input v-model="address.postal_code" placeholder="选填" clearable />
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="activeStep > 0" @click="handlePrevStep">上一步</el-button>
        <el-button type="primary" :loading="submitting" @click="handleNextOrSubmit">
          {{ activeStep === lastStep ? "提交建档" : "下一步" }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from "vue";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadRequestOptions
} from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import auditApi, { type LicenseOcrResult } from "@/api/system/org/audit";
import type { OrganizationListItem } from "@/api/system/org/organization";
import type { RegionItem } from "@/api/system/region/region";
import { uploadFile } from "@/utils/upload";

type AddressType = "shipping" | "billing";

interface AddressFormState {
  key: number;
  address_type: AddressType;
  contact_name: string;
  contact_phone: string;
  province: string;
  city: string;
  district: string;
  address: string;
  postal_code: string;
  is_default: boolean;
}

const props = defineProps<{
  visible: boolean;
  regions?: RegionItem[];
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "success", organization: OrganizationListItem | null): void;
}>();

const visibleLocal = ref(props.visible);
const activeStep = ref(0);
const lastStep = 3;
const submitting = ref(false);

const accountFormRef = ref<FormInstance>();
const companyFormRef = ref<FormInstance>();
const invoiceFormRef = ref<FormInstance>();
const addressFormRefs = ref(new Map<number, FormInstance>());

const phonePattern = /^1\d{10}$/;
const accountForm = reactive({
  phone: "",
  password: "",
  confirmPassword: "",
  nickname: "",
  real_name: ""
});

const validateConfirmPassword = (_rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error("请再次输入密码"));
  } else if (value !== accountForm.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const accountRules: FormRules = {
  phone: [
    { required: true, message: "请输入登录手机号", trigger: "blur" },
    { pattern: phonePattern, message: "请输入11位手机号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请设置登录密码", trigger: "blur" },
    { min: 6, message: "密码至少 6 位", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" }
  ],
  nickname: [{ max: 50, message: "昵称不超过50个字符", trigger: "blur" }],
  real_name: [{ max: 50, message: "姓名不超过50个字符", trigger: "blur" }]
};

const companyForm = reactive({
  company_name: "",
  license_code: "",
  legal_rep: "",
  address: "",
  region_id: undefined as number | undefined,
  scope: "",
  license_photo: ""
});

const companyRules: FormRules = {
  company_name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  license_code: [{ required: true, message: "请输入统一社会信用代码", trigger: "blur" }],
  legal_rep: [{ required: true, message: "请输入法人代表", trigger: "blur" }],
  address: [{ required: true, message: "请输入注册地址", trigger: "blur" }],
  region_id: [{ required: true, message: "请选择所属区域", trigger: "change" }],
  license_photo: [{ required: true, message: "请上传营业执照", trigger: "change" }]
};

const invoiceEnabled = ref(true);
const invoiceForm = reactive({
  invoice_title: "",
  invoice_taxno: "",
  bank_name: "",
  bank_account: "",
  bank_account_name: "",
  contact_name: "",
  contact_phone: "",
  contact_email: ""
});

const invoiceRules: FormRules = {
  invoice_title: [{ required: true, message: "请输入开票抬头", trigger: "blur" }],
  invoice_taxno: [{ required: true, message: "请输入纳税识别号", trigger: "blur" }],
  contact_phone: [
    { pattern: /^(\d{3,4}-?\d{7,8}|1\d{10})$/, message: "请输入合法的联系电话", trigger: "blur" }
  ],
  contact_email: [
    { type: "email", message: "请输入合法的邮箱地址", trigger: "blur" }
  ]
};

const addressSeed = ref(1);
const addressList = ref<AddressFormState[]>([]);

const addressRules: FormRules = {
  contact_name: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  contact_phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
  address: [{ required: true, message: "请输入详细地址", trigger: "blur" }]
};

const licenseUploading = ref(false);
const licenseUploadProgress = ref(0);
const licenseOcrRaw = ref<Record<string, any> | null>(null);

const regionOptions = computed(() => {
  const list = props.regions ?? [];
  const results: Array<{ value: number; label: string }> = [];
  const traverse = (items: RegionItem[]) => {
    items.forEach(item => {
      const isTopLevel = item.parent_id === 0 || item.level === 1;
      if (isTopLevel) {
        results.push({
          value: item.id,
          label: item.full_path || item.label || item.name
        });
      }
      if (item.children && item.children.length) {
        traverse(item.children);
      }
    });
  };
  traverse(list);
  return results;
});

const setAddressFormRef = (key: number) => (form: FormInstance | null) => {
  if (!form) {
    addressFormRefs.value.delete(key);
  } else {
    addressFormRefs.value.set(key, form);
  }
};

const createAddress = (type: AddressType, isDefault = false): AddressFormState => ({
  key: addressSeed.value++,
  address_type: type,
  contact_name: accountForm.real_name || "",
  contact_phone: accountForm.phone || "",
  province: "",
  city: "",
  district: "",
  address: "",
  postal_code: "",
  is_default: type === "shipping" ? isDefault : false
});

const ensureDefaultShipping = () => {
  const shippingList = addressList.value.filter(item => item.address_type === "shipping");
  if (!shippingList.length) return;
  if (!shippingList.some(item => item.is_default)) {
    shippingList[0].is_default = true;
  }
};

const addAddress = (type: AddressType) => {
  addressList.value.push(createAddress(type, type === "shipping" && !addressList.value.length));
  nextTick(() => ensureDefaultShipping());
};

const removeAddress = (key: number) => {
  addressList.value = addressList.value.filter(item => item.key !== key);
  nextTick(() => ensureDefaultShipping());
};

const handleDefaultToggle = (address: AddressFormState) => {
  if (!address.is_default) {
    ensureDefaultShipping();
    return;
  }
  addressList.value.forEach(item => {
    if (item.key !== address.key && item.address_type === "shipping") {
      item.is_default = false;
    }
  });
  ensureDefaultShipping();
};

const copyCompanyAddress = () => {
  if (!companyForm.address) {
    ElMessage.warning("请先填写企业注册地址");
    return;
  }
  if (!addressList.value.length) {
    addAddress("shipping");
  }
  const target = addressList.value[0];
  target.address = companyForm.address;
};

const beforeLicenseUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.warning("仅支持上传图片格式的营业执照");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.warning("营业执照图片大小不能超过 2MB");
    return false;
  }
  return true;
};

const applyLicenseOcrResult = (info: LicenseOcrResult) => {
  if (!info) return;
  if (info.company_name) companyForm.company_name = info.company_name;
  const licenseCode = info.business_license_number ?? info.license_code ?? "";
  if (licenseCode) companyForm.license_code = licenseCode;
  if (info.legal_representative) companyForm.legal_rep = info.legal_representative;
  if (info.company_address) companyForm.address = info.company_address;
  if (info.business_scope) {
    companyForm.scope = info.business_scope;
  }
  if (!invoiceForm.invoice_title && info.company_name) {
    invoiceForm.invoice_title = info.company_name;
  }
  if (!invoiceForm.invoice_taxno && licenseCode) {
    invoiceForm.invoice_taxno = licenseCode;
  }
  licenseOcrRaw.value = info.raw ?? null;
};

const recognizeLicense = async (imageUrl: string) => {
  try {
    const res = await auditApi.recognizeLicense(imageUrl);
    const ok = (res.success ?? false) || res.code === 200;
    if (ok && res.data) {
      applyLicenseOcrResult(res.data as LicenseOcrResult);
      ElMessage.success("营业执照识别成功，已自动填写信息");
    } else {
      ElMessage.warning(res.msg ?? "营业执照识别失败，请手动填写信息");
    }
  } catch (error: any) {
    ElMessage.warning(error?.message ?? "营业执照识别失败，请稍后重试");
  }
};

const handleLicenseUpload = (options: UploadRequestOptions) => {
  licenseUploading.value = true;
  licenseUploadProgress.value = 0;
  uploadFile(
    options,
    percent => {
      licenseUploadProgress.value = typeof percent === "number" ? percent : 0;
    },
    async url => {
      companyForm.license_photo = url;
      licenseUploading.value = false;
      licenseUploadProgress.value = 100;
      ElMessage.success("营业执照上传成功");
      companyFormRef.value?.clearValidate?.(["license_photo"]);
      await recognizeLicense(url);
    },
    error => {
      licenseUploading.value = false;
      licenseUploadProgress.value = 0;
      ElMessage.error(error || "上传失败，请重试");
    }
  );
};

const removeLicensePhoto = () => {
  companyForm.license_photo = "";
  licenseUploadProgress.value = 0;
  licenseOcrRaw.value = null;
  companyFormRef.value?.validateField?.("license_photo");
};

const previewLicense = () => {
  if (!companyForm.license_photo) return;
  window.open(companyForm.license_photo, "_blank");
};

const deriveContactFallback = () => companyForm.legal_rep || companyForm.company_name || "";

const ensureContactDefaults = () => {
  const fallbackName = deriveContactFallback();
  if (!accountForm.real_name && fallbackName) {
    accountForm.real_name = fallbackName;
  }
  if (!accountForm.nickname && fallbackName) {
    accountForm.nickname = fallbackName;
  }
  if (invoiceEnabled.value) {
    if (!invoiceForm.contact_name && fallbackName) {
      invoiceForm.contact_name = fallbackName;
    }
    if (!invoiceForm.contact_phone && accountForm.phone) {
      invoiceForm.contact_phone = accountForm.phone;
    }
    if (!invoiceForm.invoice_title && companyForm.company_name) {
      invoiceForm.invoice_title = companyForm.company_name;
    }
    if (!invoiceForm.invoice_taxno && companyForm.license_code) {
      invoiceForm.invoice_taxno = companyForm.license_code;
    }
  }
};

const resetForms = () => {
  activeStep.value = 0;
  accountFormRef.value?.resetFields?.();
  accountForm.phone = "";
  accountForm.password = "";
  accountForm.confirmPassword = "";
  accountForm.nickname = "";
  accountForm.real_name = "";

  companyFormRef.value?.resetFields?.();
  companyForm.company_name = "";
  companyForm.license_code = "";
  companyForm.legal_rep = "";
  companyForm.address = "";
  companyForm.region_id = undefined;
  companyForm.scope = "";
  companyForm.license_photo = "";
  licenseOcrRaw.value = null;

  invoiceFormRef.value?.resetFields?.();
  invoiceEnabled.value = true;
  invoiceForm.invoice_title = "";
  invoiceForm.invoice_taxno = "";
  invoiceForm.bank_name = "";
  invoiceForm.bank_account = "";
  invoiceForm.bank_account_name = "";
  invoiceForm.contact_name = "";
  invoiceForm.contact_phone = "";
  invoiceForm.contact_email = "";
  invoiceForm.invoice_title = "";
  invoiceForm.invoice_taxno = "";

  addressList.value = [createAddress("shipping", true)];
  licenseUploading.value = false;
  licenseUploadProgress.value = 0;
};

const handleClose = () => {
  visibleLocal.value = false;
  emit("update:visible", false);
  resetForms();
};

const validateCurrentStep = async () => {
  if (activeStep.value === 0 && accountFormRef.value) {
    await accountFormRef.value.validate();
    return true;
  }
  if (activeStep.value === 1 && companyFormRef.value) {
    await companyFormRef.value.validate();
    return true;
  }
  if (activeStep.value === 2) {
    if (!invoiceEnabled.value) {
      return true;
    }
    if (invoiceFormRef.value) {
      await invoiceFormRef.value.validate();
      return true;
    }
  }
  if (activeStep.value === 3) {
    if (!addressList.value.length) {
      ElMessage.error("请至少新增一个地址");
      return false;
    }
    for (const address of addressList.value) {
      const formRef = addressFormRefs.value.get(address.key);
      if (formRef) {
        await formRef.validate();
      }
      if (!address.contact_name || !address.contact_phone || !address.address) {
        ElMessage.error("请完善地址信息");
        return false;
      }
    }
    const hasShipping = addressList.value.some(item => item.address_type === "shipping");
    if (!hasShipping) {
      ElMessage.error("请至少保留一个收货地址");
      return false;
    }
    ensureDefaultShipping();
    return true;
  }
  return true;
};

const buildPayload = () => {
  ensureContactDefaults();

  const account = {
    phone: accountForm.phone,
    password: accountForm.password,
    nickname: accountForm.nickname,
    real_name: accountForm.real_name
  };

  const company: Record<string, any> = {
    company_name: companyForm.company_name,
    license_code: companyForm.license_code,
    legal_rep: companyForm.legal_rep,
    address: companyForm.address,
    region_id: companyForm.region_id,
    scope: companyForm.scope,
    license_photo: companyForm.license_photo
  };
  if (licenseOcrRaw.value) {
    company.license_raw = licenseOcrRaw.value;
  }

  const invoice =
    invoiceEnabled.value && (invoiceForm.invoice_title || invoiceForm.invoice_taxno)
      ? { ...invoiceForm }
      : {};

  const addresses = addressList.value.map(item => ({
    address_type: item.address_type,
    contact_name: item.contact_name,
    contact_phone: item.contact_phone,
    province: item.province,
    city: item.city,
    district: item.district,
    address: item.address,
    postal_code: item.postal_code,
    is_default: item.is_default ? 1 : 0
  }));

  return { account, company, invoice, addresses };
};

const submitQuickCreate = async () => {
  submitting.value = true;
  try {
    const payload = buildPayload();
    const response = await auditApi.fastCreate(payload);
    const organization = (response.data?.org ?? null) as OrganizationListItem | null;
    ElMessage.success("组织建档成功");
    emit("success", organization);
    handleClose();
  } catch (error: any) {
    const message = error?.message ?? error?.response?.data?.message ?? "建档失败";
    ElMessage.error(message);
  } finally {
    submitting.value = false;
  }
};

const handlePrevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value -= 1;
  }
};

const handleNextOrSubmit = async () => {
  const valid = await validateCurrentStep().catch(() => false);
  if (!valid) return;
  if (activeStep.value === lastStep) {
    await submitQuickCreate();
  } else {
    activeStep.value += 1;
  }
};

watch(
  () => props.visible,
  value => {
    visibleLocal.value = value;
    if (value) {
      resetForms();
    }
  }
);

watch(
  () => [companyForm.legal_rep, companyForm.company_name],
  () => {
    const fallback = deriveContactFallback();
    if (fallback) {
      if (!accountForm.real_name) accountForm.real_name = fallback;
      if (!accountForm.nickname) accountForm.nickname = fallback;
      if (!invoiceForm.contact_name) invoiceForm.contact_name = fallback;
    }
  }
);

watch(
  () => accountForm.phone,
  phone => {
    if (invoiceEnabled.value && phone && !invoiceForm.contact_phone) {
      invoiceForm.contact_phone = phone;
    }
  }
);
</script>

<style scoped>
.quick-create {
  display: flex;
  flex-direction: column;
}

.step-container {
  margin-top: 8px;
}

.address-list :deep(.el-card__header) {
  padding: 12px 16px;
}

.license-upload {
  width: 100%;
}

.license-upload__placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  color: var(--el-text-color-secondary);
}

.license-upload__icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.license-upload__text .title {
  font-size: 14px;
  margin-bottom: 4px;
}

.license-upload__text .hint {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.license-preview {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.license-preview__image {
  max-width: 100%;
  max-height: 220px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.license-preview__actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.license-progress {
  margin-top: 8px;
  width: 240px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
